var React = require('react');
var _ = require('underscore');
var API = require('../../../business_platform/api/api');

require("./area-city.scss");
var AreaCity = React.createClass({
  propTypes: {
    value: React.PropTypes.any,
    onChange: React.PropTypes.func,
  },
  getInitialState() {
    this.result = {};
    return {
      areaData: [],
      cityData: [],
      defaultSelect: this.props.defaultSelect
    };
  },
  componentDidMount() {
    var defaultSelect = this.state.defaultSelect;
    if(defaultSelect){
        $.ajax({
          url: API.getBankArea,
        }).done(data => {
          this.result.areaId = defaultSelect[0];
          this.result.areaName = defaultSelect[0];
          this.setState({
            areaData: data.result,
            defaultArea:defaultSelect ? defaultSelect[0] : ""
          });
        });
      $.ajax({
        url: API.getBankCity + '?areaName=' + encodeURI(defaultSelect[0]),
      }).done(data => {
        this.result.cityId = defaultSelect[1];
        this.result.cityName = defaultSelect[1];
        this.setState({
          cityData: data.result,
          defaultCity:defaultSelect ? defaultSelect[1] : ""
        });
      });
    }else{
      $.ajax({
        url: API.getBankArea,
      }).done(data => {
        this.setState({
          areaData: data.result,
          defaultSelect:this.props.defaultSelect
        });
      });
    }

  },
  onAreaChange(event) {
    var areaName = event.target.value;
    $.ajax({
      url: API.getBankCity + '?areaName=' + encodeURI(areaName),
    }).done(data => {
      this.setState({
        cityData: data.result
      });
    });
    this.setState({
      cityData: [],
      defaultSelect : undefined
    });
    this.result.areaName = areaName;
    this.result.cityName = undefined;
    this.props.onChange({
      data : this.result,
      type : "area"
    });
  },
  onCityChange(event) {
    var cityName = event.target.value;
    this.result.cityName = cityName;
    this.props.onChange({
      data : this.result,
      type : "areaCity"
    });
  },
  render() {
    var { onChange, ...others} = this.props;
    var { areaData, cityData,defaultArea,defaultCity} = this.state;
    if(!!this.props.defaultSelect){
      if(!defaultArea || !defaultCity){
        return null;
      }
    }
    return (<div className="area-city-mod" {...others} style={{display: 'inline-block'}}>
      <select defaultValue={defaultArea} name="" className="half" style={{marginLeft:0}} onChange={this.onAreaChange}>
        <option value="0">请选择区域</option>
        {areaData.map((area,index) => <option value={area} key={index}>{area}</option>)}
      </select>
      <select defaultValue={defaultCity} name="" id="" className="half" onChange={this.onCityChange}>
        <option value="0">请选择城市</option>
        {cityData.map((city,index) => <option value={city} key={index}>{city}</option>)}
      </select>
    </div>);
  }
});

module.exports = AreaCity;